from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from sts.sts import Sts
from qcloud_cos.cos_exception import CosClientError, CosServiceError
import json

secret_id = 'AKIDrYy80bw0nKaZHjtmOjna6KIVS8YhY9TX'     # 替换为用户的 SecretId，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
secret_key = 'oLaZHhrlOkpdBRQ8akdFbgU1GEwNXR4R'   # 替换为用户的 SecretKey，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
token = None               # 如果使用永久密钥不需要填入token，如果使用临时密钥需要填入，临时密钥生成和使用指引参见https://cloud.tencent.com/document/product/436/14048
scheme = 'https'           # 指定使用 http/https 协议来访问 COS，默认为 https，可不填

user_folder = 'user/'
device_folder = 'device/'
basic_folder = 'basic/'



appId = 1300357628
base_bucket = 'seubilibili-1300357628'
base_region = 'ap-nanjing'
base_url = 'https://seubilibili-1300357628.cos.ap-nanjing.myqcloud.com/'

if secret_id != '':
    config = CosConfig(Region=base_region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)
    client = CosS3Client(config)
else:
    config = None
    client = None

 # 配置CROS以及创建存储桶
crosConfig = {
                'CORSRule': [
                    {
                        'ID': '1',
                        'MaxAgeSeconds': 5,
                        'AllowedOrigin': [
                            'https://*',
                            'http://*'
                        ],
                        'AllowedMethod': [
                            'PUT',
                            'GET',
                            'POST',
                            'HEAD',
                        ],
                        'AllowedHeader': [
                            '*',
                        ],
                        'ExposeHeader': [
                            'ETag',
                            'Content-Length',
                            'x-cos-request-id',
                        ]
                    }
                ]
            }

try:
    client.get_bucket_cors(Bucket=base_bucket)
except Exception as r:
    print(r,'开始创建base跨域策略')
    try:
        client.put_bucket_cors(
            Bucket=base_bucket,
            CORSConfiguration=crosConfig,
        )
    except Exception as r:
        print('error')


def object_exist_tencent(bucket,key):
    response = client.object_exists(
    Bucket=bucket,
    Key=key)
    return response


def upload_files_tencent(localfile, filename, base_bucket):
    # 使用高级接口断点续传，失败重试时不会上传已成功的分块(这里重试10次)
    print(base_bucket)
    for i in range(0, 10):
        try:
            response = client.upload_file(
            Bucket=base_bucket,
            Key=filename,
            LocalFilePath=localfile)
            break
        except CosClientError or CosServiceError as e:
            print(e)
    return response


def put_object_tencent(inputdata, filename, base_bucket):
    response = client.put_object(
        Bucket=base_bucket,  # Bucket 由 BucketName-APPID 组成
        Body=inputdata,
        Key=filename,
        StorageClass='STANDARD',
        ContentType='text/html; charset=utf-8'
    )
    print(response)
    return response['ETag']


def delete_file_tencent(bucket_name, key):
    response = client.delete_object(
        Bucket=bucket_name,
        Key=key
    )
    return response


def get_credential_demo():
    global base_region, base_region
    bucket = base_bucket
    region = base_region
    allow_prefix = '*'
    config = {
        'url': 'https://sts.tencentcloudapi.com/',
        # 域名，非必须，默认为 sts.tencentcloudapi.com
        'domain': 'sts.tencentcloudapi.com',
        # 临时密钥有效时长，单位是秒
        'duration_seconds': 1800,
        'secret_id': secret_id,
        # 固定密钥
        'secret_key': secret_key,
        # 设置网络代理
        # 'proxy': {
        #     'http': 'xx',
        #     'https': 'xx'
        # },
        # 换成你的 bucket
        'bucket': bucket,
        # 换成 bucket 所在地区
        'region': region,
        # 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径
        # 例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
        'allow_prefix': allow_prefix,
        # 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
        'allow_actions': [
            # 简单上传
            'name/cos:PutObject',
            'name/cos:PostObject',
            # 分片上传
            'name/cos:InitiateMultipartUpload',
            'name/cos:ListMultipartUploads',
            'name/cos:ListParts',
            'name/cos:UploadPart',
            'name/cos:CompleteMultipartUpload',

            'name/cos:HeadObject',
            
            'name/cos:GetObject',
        ],
    }

    try:
        sts = Sts(config)
        response = sts.get_credential()
        return json.dumps({'success': True, 'response': dict(response)})
    except Exception as e:
        print(e)
        return json.dumps({'success': False})

